import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/user.dart';
import 'package:ichinesereader/exam/dto/assessment.response.dart';
import 'package:ichinesereader/models/book/BookQuiz.dart';
import 'package:ichinesereader/models/book/BookQuizAnswerDto.dart';
import 'package:ichinesereader/models/book/BookQuizResult.dart';
import 'package:ichinesereader/models/book/BookQuizQuestion.dart';
import 'package:ichinesereader/models/common/StatusMessageResult.dart';
import 'package:ichinesereader/pages/common/bookSettings.dart';
import 'package:ichinesereader/service/book.dart';
import 'package:ichinesereader/utils/StrUtil.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/controller/books.dart';

class BookQuizController extends GetxController with StateMixin<dynamic> {
  BookServiceProvider _bookServiceProvider = new BookServiceProvider();
  Rx<BookQuiz> _bookquiz = Rx<BookQuiz>(BookQuiz());
  Rx<BookQuiz> get bookquiz => this._bookquiz;
  Rx<StatusMessageResult> _statusMessageResult =
      Rx<StatusMessageResult>(StatusMessageResult());
  Rx<StatusMessageResult> get statusMessageResult => this._statusMessageResult;
  final BooksController _booksController = Get.find();
  final UserController _usersController = Get.find();
  @override
  void onInit() {
    super.onInit();
  }

  @override
  dispose() {
    super.dispose();
  }

  void fetchBookQuiz(String bookId) async {
    try {
      EasyLoading.show();
      var response = await _bookServiceProvider.getBookQuiz(bookId);
      if (response.statusCode == 200) {
        var data = bookQuizFromJson(response.bodyString);
        _bookquiz.value = data;
        change(_bookquiz, status: RxStatus.success());
      } else {
        change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
        Log.debug(response.body);
      }
    } catch (error) {
      change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
  }

  Future<BookQuiz> getBookQuiz(
      String bookId, TextOptions textOptions, AudioOptions audioOptions) async {
    var quiz = BookQuiz();
    try {
      var response = await _bookServiceProvider.getBookQuiz(bookId);
      if (response.statusCode == 200) {
        quiz = bookQuizFromJson(response.bodyString);
      }
    } catch (error) {
      Log.debug(error);
    }
    return quiz;
  }

  List<QuestionItem> fromBookQuizToQuestionItems(
      BookQuiz bookQuiz, TextOptions textOptions, AudioOptions audioOptions) {
    List<QuestionItem> questionItems = [];
    List<QuizQuestion> bookQQuestions = bookQuiz.questions!;

    bookQQuestions.forEach((quizQuestion) {
      var questionItem = QuestionItem();
      List<List<QuestionContent>> questionBodyItems = [];
      List<String> showItems = [];
      var showItemsString = '';
      if (quizQuestion.simpQuestion != null &&
          quizQuestion.simpQuestion != '') {
        showItems.add('text');
      }
      if (quizQuestion.questionImage != null &&
          quizQuestion.questionImage != '') {
        showItems.add('image');
      }
      if (quizQuestion.questionAudio != null &&
          quizQuestion.questionAudio != '') {
        showItems.add('audio');
      }
      showItemsString = showItems.join('|');

      questionItem.type = 'option';
      questionItem.number = int.tryParse(quizQuestion.id.toString()) ?? 1;
      questionItem.head = QuestionContent(
        audio: quizQuestion.questionAudio != null &&
                quizQuestion.questionAudio != ''
            ? audioOptions == AudioOptions.Mandarin
                ? '${bookQuiz.baseResourceUrl}${quizQuestion.questionAudio}'
                : _getCantoneseAudioLink(
                    '${bookQuiz.baseResourceUrl}${quizQuestion.questionAudio}')
            : null,
        show: showItemsString,
        text: textOptions == TextOptions.Simplified
            ? quizQuestion.simpQuestion
            : quizQuestion.tradQuestion,
        image: quizQuestion.questionImage != null &&
                quizQuestion.questionImage != ''
            ? '${bookQuiz.baseResourceUrl}${quizQuestion.questionImage}'
            : '',
      );

      List<QuestionContent> bodyItems = [];
      questionItem.solution = [];

      quizQuestion.answers?.forEach((answer) {
        var basevalue = '';
        if (answer.simpAnswer != null && answer.simpAnswer != '') {
          basevalue = textOptions == TextOptions.Simplified
              ? answer.simpAnswer.toString()
              : answer.tradAnswer.toString();
        } else {
          if (answer.answerImage != null && answer.answerImage != '') {
            basevalue = answer.answerImage.toString();
          }
        }

        showItems = [];
        showItemsString = '';
        if (answer.simpAnswer != null && answer.simpAnswer != '') {
          showItems.add('text');
        }
        if (answer.answerImage != null && answer.answerImage != '') {
          showItems.add('image');
        }
        if (answer.answerAudio != null && answer.answerAudio != '') {
          showItems.add('audio');
        }
        showItemsString = showItems.join('|');
        bodyItems.add(QuestionContent(
            baseValue: basevalue,
            image: answer.answerImage != null && answer.answerImage != ''
                ? '${bookQuiz.baseResourceUrl}${answer.answerImage}'
                : '',
            audio: audioOptions == AudioOptions.Mandarin
                ? '${bookQuiz.baseResourceUrl}${answer.answerAudio}'
                : _getCantoneseAudioLink(
                    '${bookQuiz.baseResourceUrl}${answer.answerAudio}'),
            text: textOptions == TextOptions.Simplified
                ? answer.simpAnswer
                : answer.tradAnswer,
            show: showItemsString));
        // print(
        //     '${bookQuiz.baseResourceUrl}${answer.answerAudio?.replaceAll('.mp3', 't.mp3')}');
        if (answer.isCorrect != null && answer.isCorrect == true) {
          questionItem.solution?.add(textOptions == TextOptions.Simplified
              ? answer.simpAnswer.toString()
              : answer.tradAnswer.toString());
        }
      });

      questionBodyItems.add(bodyItems);
      questionItem.body = questionBodyItems;

      if (bookQuiz.currentMaxScore != null) {
        questionItem.answer = [];
        // var _submittedAnswers =
        //     bookQuiz.currentMaxScore?.submittedAnswers![questionItem.number];
        questionItem.answer = bookQuiz
                .currentMaxScore?.submittedAnswers!['${questionItem.number}'] ??
            null;
      }
      questionItems.add(questionItem);
    });
    return questionItems;
  }

  String _getCantoneseAudioLink(String mLink) {
    var fileName = StrUtil.splitStringByIndex(mLink, mLink.lastIndexOf('/'))[1];
    var link = mLink.replaceAll(fileName, 'c$fileName');
    return link;
  }

  Future<dynamic> postBookQuizAnswer(
      String bookId, BookQuizAnswerDto dto) async {
    EasyLoading.show();
    var quizResult = BookQuizResult();
    try {
      var response = await _bookServiceProvider.postBookQuizAnswer(bookId, dto);
      if (response.statusCode == 200) {
        quizResult = bookQuizResultFromJson(response.bodyString);
        _booksController.resetBookStatus(bookId, quizResult.percentage!);
        if (quizResult.percentage! >= 75) {
          _usersController.refreshLevelPercentage();
        }
      }
    } catch (error) {
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
    return quizResult;
  }

  void fetchAssignmentBookQuiz(String bookId, String assignmentId) async {
    try {
      //change(_bookquiz, status: RxStatus.loading());
      EasyLoading.show();
      var response = await _bookServiceProvider.getAssignmentBookQuiz(
          bookId, assignmentId);
      if (response.statusCode == 200) {
        var data = bookQuizFromJson(response.bodyString);
        _bookquiz.value = data;
        change(_bookquiz, status: RxStatus.success());
      } else {
        change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
        Log.debug(response.body);
      }
    } catch (error) {
      change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
  }

  Future<BookQuiz> getAssignmentBookQuiz(
      String bookId, String assignmentId) async {
    var quiz = BookQuiz();
    try {
      var response = await _bookServiceProvider.getAssignmentBookQuiz(
          bookId, assignmentId);
      if (response.statusCode == 200) {
        quiz = bookQuizFromJson(response.bodyString);
      }
    } catch (error) {
      Log.debug(error);
    }
    return quiz;
  }

  Future<dynamic> postAssignmentBookQuizAnswer(
      String bookId, String assignmentId, BookQuizAnswerDto dto) async {
    EasyLoading.show();
    var quizResult = BookQuizResult();
    try {
      var response = await _bookServiceProvider.postAssignmentBookQuizAnswer(
          bookId, assignmentId, dto);
      if (response.statusCode == 200) {
        quizResult = bookQuizResultFromJson(response.bodyString);
        _booksController.resetBookStatus(bookId, quizResult.percentage!);
      }
    } catch (error) {
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
    return quizResult;
  }
}
